package com.hopu.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.hopu.context.BaseContext;
import com.hopu.entity.Result;
import com.hopu.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;



@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override//目标资源方法运行前运行,返回true,放行,返回false,不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取url
        String url = request.getRequestURI().toString();
        log.info("请求的url: {}", url);

        //判断是否为登录请求
        //是直接放行
        if (url.contains("login")||url.contains("register")||url.contains("video")) {
            log.info("登录或注册操作,放行...");
            return true;
        }

        //获取请求头中的令牌
       //String jwt = request.getHeader("token");
        //用路径来获取
        String token = request.getParameter("token");
        if (!(token != null && !token.isEmpty())) {
            log.info("请求头token为空,返回未登录信息");
            //返回给前端这个结果,前端跳转到登录页面
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        //解析令牌
        try {
            //获取当前用户id
            Integer userId = jwtUtils.getUserIdFromJwt(token);
            //存入,供后续业务使用
            BaseContext.setCurrentId(userId);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败,返回未登录信息");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        //令牌合法,放行
        return true;

    }

    @Override//目标资源方法运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override//视图渲染完毕后运行,最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
